package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import com.itheima.utils.AppJwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author itheima
 * @Date 2022/5/5 12:02
 */
@RestController
@RequestMapping("/employee")
@Slf4j
@Api(tags = "员工管理")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    /**
     * 登录：
     * 1.请求：POST http://localhost:8080/employee/login
     * 2.{"username":"admin","password":"123456"}--反序列化--->Employee或者Map集合
     * 3.响应：{"code":,"data":Employee对象,"msg":}
     */
    @PostMapping("/login")
    @ApiOperation("员工登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "map", value = "登录账号和密码数据")})
    public R<Employee> login(@RequestBody Map<String, String> map, HttpSession session) {
        String username = map.get("username");
        String password = map.get("password");
        //登录实现：账号、密码 、账号状态  卫语句实现多个条件判断
        //1.通过查询数据库表校验账号是否存在
        QueryWrapper<Employee> qw = new QueryWrapper<>();
        //select * from employee  where username=?
        qw.eq(StringUtils.isNotBlank(username), "username", username);
        Employee employee = employeeService.getOne(qw);
        //账号
        if (employee == null) {
            return R.error("账号不存在！");
        }

        //2.用户输入的密码进行加密和数据库中密码进行比对
        //使用md5加密后的密码
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Pass.equals(employee.getPassword())) {
            return R.error("密码输入错误！");
        }

        //3.查询数据库表中的账号是否是正常
        if (employee.getStatus() == 0) {
            return R.error("账号已经禁用！");
        }

        //产生一个token返回给客户端
        String token = AppJwtUtil.getToken(employee.getId());
        R<Employee> r = R.success(employee);
        r.add("token", token);
        return r;
    }

    /**
     * 退出
     * 1.请求：POST http://localhost:8080/employee/logout
     * 2.参数：无参数
     * 3.响应：{code:1,msg:"",data:"退出成功"}
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session, HttpServletResponse response) {
        return R.success("退出成功！");
    }

    /**
     * 新增员工
     * 1.POST ：http://localhost:8080/employee
     * 2.发送参数：{"name":"王五","phone":"18812341234","sex":"1","idNumber":"420921123412341234","username":"user5"}
     * 3.响应结果：
     * 成功：{code:1,msg:"",data:""}
     * 失败：{code:0,msg:"错误信息",data:""}
     */
    @PostMapping
    public R<String> saveEmployee(@RequestBody Employee employee, HttpSession session) {
        log.info("线程名称{},线程id{}", Thread.currentThread().getName(), Thread.currentThread().getId());
        //1.MP自动给employee填充设置其他属性
        //2.给employee设置初始化密码 123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'user4' for key 'idx_username'
        employeeService.save(employee);
        return R.success("保存成功！");
    }

    /**
     * 分页查询：
     * 1.请求：GET http://localhost:8080/employee/page?page=1&pageSize=10&name=tom4
     * 2.响应：{code:1,data:分页对象,msg:}
     */
    @GetMapping("/page")
    public R<Page<Employee>> pageEmployee(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize, String name) {
        Page<Employee> page1 = new Page<>(page, pageSize);
        //select  * from   employee where name like ?  order by update_time desc limit ?,?;
        QueryWrapper<Employee> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(name), "name", name);
        qw.orderByDesc("update_time");
        Page<Employee> pageResult = employeeService.page(page1, qw);
        return R.success(pageResult);
    }

    /**
     * 修改状态
     * 1.请求：PUT http://localhost:8080/employee
     * 2.参数：{"id":1522418477585952800,"status":0}
     * 3.响应：{code:1,data:"修改操作成功",msg:}
     */
    @PutMapping
    public R<String> updateEmployee(@RequestBody Employee employee, HttpSession session) {
        employee.setUpdateUser(null);
        employee.setUpdateTime(null);
        //修改更新时间和用户
        employeeService.updateById(employee);
        return R.success("修改操作成功");
    }

    /**
     * 员工详情：
     * 1.请求：GET http://localhost:8080/employee/1511601332561629186
     * 2.响应：{code:1,data:查询员工对象,msg:}
     */
    @GetMapping("/{id}")
    public R<Employee> queryEmployee(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee == null) {
            return R.error("查询没有该员工！");
        }
        return R.success(employee);
    }
}
